<template>
	<view class="post-container" style="padding: 10px;">
		<u--form labelPosition="left" :model="post" ref="form1">
			<u-form-item labelWidth=100 label="帖子标题" prop="title" borderBottom ref="item1">
				<u--input v-model="post.title" border="none" placeholder="请填写帖子标题"></u--input>
			</u-form-item>
			<u-form-item labelWidth=100 label="内容" prop="content" borderBottom ref="item3">
				<u--textarea placeholder="请填写你的分享内容捏!" v-model="post.content"></u--textarea>
			</u-form-item>
			<u-form-item labelWidth=80px label="照片" prop="pictures" borderBottom>
				<u-upload :previewFullImage="true" :fileList="fileList1" @afterRead="afterRead" @delete="deletePic"
					name="1" multiple :maxCount="6" @beforeRead="beforeRead"></u-upload>
			</u-form-item>
		</u--form>

		<u-button type="primary" text="发布" customStyle="margin-top: 50px" @click="savaOrUpdate"></u-button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				pictureList: [],
				fileList1: [],
				post: {
					title: '',
					content: '',
					pictures: '',
					userId: ''
				},
				rules: {
					'title': {
						type: 'string',
						required: true,
						message: '此为必填字段',
						trigger: ['blur', 'change']
					},
					'content': {
						type: 'string',
						required: true,
						message: '请填写描述，你不描述我咋认领找回呢',
						trigger: ['blur', 'change']
					}
				},
			};
		},
		onLoad(options) {
			// console.log(options);
			if (options.id) {
				this.getById(options.id)
			}
			this.post.userId = uni.getStorageSync('userInfo').id
		},
		onReady() {
			//onReady 为uni-app支持的生命周期之一
			this.$refs.form1.setRules(this.rules)
		},
		methods: {
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			async afterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				// 用于存储符合条件的图片
				let Images = [];
				// 遍历上传的每张图片
				for (let i = 0; i < lists.length; i++) {
					const item = lists[i];
					// 验证图片格式
					const isImage = /\.(png|jpe?g)$/i.test(item.url);
					if (!isImage) {
						uni.showToast({
							title: '只能上传png，jpg，jpeg格式的图片',
							icon: 'none',
							duration: 3000
						});
						// 删除不符合条件的图片
						lists.splice(i, 1);
						// 跳过当前图片，进行下一张图片的验证
						continue;
					}
					// 验证图片大小
					const maxSize = 2 * 1024 * 1024; // 2MB大小限制
					if (item.size > maxSize) {
						uni.showToast({
							title: '图片大小不能超过2MB',
							icon: 'none',
							duration: 3000
						});
						// 删除不符合条件的图片
						lists.splice(i, 1);
						// 跳过当前图片，进行下一张图片的验证
						continue;
					}
					Images.push(item)
				}

				let fileListLen = this[`fileList${event.name}`].length
				Images.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < Images.length; i++) {
					const result = await this.uploadFilePromise(Images[i].url)
					this.pictureList.push(result)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
				this.post.pictures = JSON.stringify(this.pictureList)
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: 'http://localhost:8099/file/user/upload',
						filePath: url,
						name: 'pic',
						header: {
							'authentication': 'eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxNzgzMDMwODgyMjU1NjkxNzc3LCJleHAiOjE3MTQ0ODc2MDV9.QD3S8GtrXar3mJUVAEBwqnKJnceMM2OnI1BNmeUh8VY'
						},
						formData: {
							biz: 'post_picture'
						},
						success: (res) => {
							res = JSON.parse(res.data)
							if (res.code === 20000) {
								setTimeout(() => {
									resolve(res.data)
								}, 1000)
							} else {
								uni.$showMsg(res.msg)
							}
						}
					});
				})
			},
			savaOrUpdate() {
				console.log(this.post);
				// 如果有错误，会在catch中返回报错信息数组，校验通过则在then中返回true
				this.$refs.form1.validate().then(res => {
					if (this.post.id) {
						this.updateById(this.post.id)
					} else {
						this.savePost()
					}
				}).catch(errors => {
					uni.$u.toast('发布失败！')
				})
			},
			async savePost() {
				let {
					data: res
				} = await uni.$http.post('/user/post', this.post)
				if (res.code === 20000) {
					setTimeout(() => {
						uni.$showMsg("发布成功！")
					}, 1500)
					uni.switchTab({
						url: '/pages/moment/moment'
					})
				} else {
					uni.$showMsg(res.msg)
				}
			},
			async updateById(id) {
				let {
					data: res
				} = await uni.$http.put('/user/post/' + id, this.post)
				if (res.code === 20000) {
					setTimeout(() => {
						uni.$showMsg("保存成功！")
					}, 1500)
					uni.switchTab({
						url: '/pages/moment/moment'
					})
				} else {
					uni.$showMsg(res.msg)
				}
			},
		}
	}
</script>

<style lang="scss">

</style>